# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exporters import JsonItemExporter
from twisted.internet import defer, reactor


# from rule_spider.models.scrapy_redis_sentinel.bloomfilter import BloomFilter



class PERMBloomFilterPipeline:
    '''
    保存永久布隆过滤器 和 图片队列
    '''

    def __init__(self, PERM_BLOOMFILTER_KEY, PERM_BLOOMFILTER_HASH_NUMBER, PERM_BLOOMFILTER_BIT, IMAGES_KEY):
        self.PERM_BLOOMFILTER_KEY = PERM_BLOOMFILTER_KEY
        self.PERM_BLOOMFILTER_HASH_NUMBER = PERM_BLOOMFILTER_HASH_NUMBER
        self.PERM_BLOOMFILTER_BIT = PERM_BLOOMFILTER_BIT
        self.IMAGES_KEY = IMAGES_KEY

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
        PERM_BLOOMFILTER_KEY=crawler.settings.get("PERM_BLOOMFILTER_KEY"),
        PERM_BLOOMFILTER_HASH_NUMBER=crawler.settings.get("PERM_BLOOMFILTER_HASH_NUMBER"),
        PERM_BLOOMFILTER_BIT=crawler.settings.get("PERM_BLOOMFILTER_BIT"),
        IMAGES_KEY=crawler.settings.get("IMAGES_KEY"),
        )

    def open_spider(self, spider):
        self.server = spider.server
        self.perm_bf = BloomFilter(spider.server, key=self.PERM_BLOOMFILTER_KEY, bit=self.PERM_BLOOMFILTER_BIT, hash_number=self.PERM_BLOOMFILTER_HASH_NUMBER)

    def process_item(self, item, spider):
        # 保存图片
        images_message = item.get("images_message")
        if images_message:
            self.server.hmset(self.IMAGES_KEY, images_message)

        # 布隆过滤器
        request_url = item.get("request_url")
        response_url = item.get("response_url")
        article_url = item.get("article_url")
        for url in {request_url, response_url, article_url}:
            self.perm_bf.insert(url)

        return item
